#include <func.h>

typedef struct {
    int id;
    char name[25];
    int balance;
    pthread_mutex_t mutex;  // 细粒度锁
} Account;

Account acct1 = {1, "peanut", 100, PTHREAD_MUTEX_INITIALIZER};
// pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  // 粗粒度锁

void cleanup(void* arg) 
{
    pthread_mutex_t* mtx = (pthread_mutex_t*) arg;
    pthread_mutex_unlock(mtx);
}

void* withdraw(void* arg) 
{
    int money = (int)arg;

    pthread_mutex_lock(&acct1.mutex);
    // 注册清理函数
    pthread_cleanup_push(cleanup, &acct1.mutex);

    if (acct1.balance < money) {
        // 在线程的每一个出口都释放锁！
        pthread_exit(NULL);
    }
    sleep(1);   // 增加某个调度出现的概率！
    acct1.balance -= money;
    printf("%lx: withdraw %d\n", pthread_self(), money);

    pthread_exit(NULL);

    pthread_cleanup_pop(0);
}

int main(int argc, char* argv[])
{
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, withdraw, (void*)100);
    pthread_create(&tid2, NULL, withdraw, (void*)100);
    
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    return 0;
}

